package com.power.service.impl;

import com.power.common.Contants;
import com.power.dao.LoginDao;
import com.power.dao.impl.LoginDaoImpl;
import com.power.ov.ResultData;
import com.power.pojo.Users;
import com.power.service.LoginService;
import com.power.utils.MD5;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/10/03 8:23
 * Description:
 * Version: V1.0
 */
public class LoginServiceImpl implements LoginService {
    LoginDao loginDao=new LoginDaoImpl();
    @Override
    public ResultData login(Users users) throws SQLException {
        ResultData resultData=new ResultData();
        try {
            users.setUser_pwd(MD5.getMD5(users.getUser_pwd()).toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
       //判断用户是否存在
        List<Map<String,Object>> list_is=loginDao.loginByIsDelete(users);
        if (list_is.size()>0){
            //判断角色是否可用
            List<Map<String,Object>> listRole=loginDao.findByRole(users);
            if (listRole.size()>0) {
                //先查用户名密码是否真确
                List<Map<String, Object>> list = loginDao.login(users);
                if (list.size() > 0) {
                    //用户成功判断是否被冻结
                    List<Map<String, Object>> list1 = loginDao.loginByStat(users);
                    if (list1.size() > 0) {
                        loginDao.updateLatly(users.getUser_account(), new Date());
                        List<Map<String, Object>> listAll = loginDao.loginByAll(users);
                        for (Map map : listAll) {
                            map.get("in_time");
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            if (map.get("in_time") != null) {
                                map.put("in_time", simpleDateFormat.format(map.get("in_time")));
                            }
                        }
                        resultData.setCode(Contants.SUCCESS);
                        resultData.setMsg("登录成功，即将跳转...");
                        resultData.setData(listAll);
                    } else {
                        resultData.setCode(Contants.FREEZE);
                        resultData.setMsg("账号已被冻结！！！请联系管理员");
                    }
                } else {
                    resultData.setCode(Contants.FAILURE);
                    resultData.setMsg("账号或密码错误");
                }
            }else {
                //角色不可用
                resultData.setCode(Contants.ROLENO);
                resultData.setMsg("当前用户角色不可用");
            }
        }else {
            resultData.setCode(Contants.NOT_NO);
            resultData.setMsg("用户不存在");
        }
        return resultData;
    }
}
